﻿// Less2DB.NET framework
// http://code.google.com/p/less2db/
//
// Copyright © Wangzhongwu, 2011
// alex.wzw@gmail.com
//

namespace Less2DB.SQLBuilder
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    class SQLUpdateBuilder : BuilderBase
    {
        public SQLUpdateBuilder(string tableName, string[] fields)
        {
            this.TableName = tableName;
            this.Fields = fields;
        }

        private string ToString(string table, string fieldsAndValues, string where)
        {
            string querystring = "UPDATE {TABLE} SET {FIELDS&VALUES} {WHERE}";

            querystring = querystring.Replace("{TABLE}", table);
            querystring = querystring.Replace("{FIELDS&VALUES}", fieldsAndValues);
            querystring = querystring.Replace("{WHERE}", where);

            return querystring;
        }

        /// <summary>
        /// 将此实例的值转换为 System.String。
        /// </summary>
        /// <returns>其值与此实例相同的字符串。</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();

            foreach (string field in this.Fields)
            {
                if (sb.Length == 0)
                {
                    sb.Append(field + " = @" + field);
                }
                else
                {
                    sb.Append(", " + field + " = @" + field);
                }
            }

            return this.ToString(this.TableName, sb.ToString(), this.Where);
        }
    }
}
